import axios from "axios";
import { Message } from "element-ui";
import {getToken} from "./app";

const BASE_URL = process.env.NODE_ENV === "production" ? "" : "http://localhost:9669/api";

const service = axios.create({
  baseURL: BASE_URL,
  timeout: 15000
});

service.interceptors.request.use(
  function(config) {
    config.headers["authorization"] = `Bearer ${getToken()}`;
    return config;
  },
  function(error) {
    return Promise.reject(error);
  }
);

service.interceptors.response.use(
  function(response) {
    const data = response.data;
    if (data.errno !== 0) {
      Message.error(JSON.stringify(data.msg));
      return Promise.reject(data);
    } else {
      return data.data;
    }
  },
  function(error) {
    console.log('error:',error);
    console.log('error.message:',error.message);
    if (error.message === "Network Error") {
      Message.error("未能连接到该API服务器,请检查网络连接~");
    } else {
      Message.error(JSON.stringify(error.response.data.msg) || "请求失败");
    }
    return Promise.reject(error);
  }
);

export default service;
